package cn.edu.ldu.protocol;

import cn.edu.ldu.modules.controller.UserAccountController;
import cn.edu.ldu.modules.entity.UserAccountEntity;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.L;
import com.alibaba.fastjson.JSON;
import cn.edu.ldu.modules.controller.FriendsController;
import cn.edu.ldu.views.modules.controller.UserController;
import cn.edu.ldu.modules.entity.FriendsEntity;

import java.io.IOException;
import java.net.DatagramPacket;

public class AddFriend {

    public AddFriend(Protocol protocol) throws IOException {

        DatagramPacket p = protocol.getPacket();

        try {
//            FriendsEntity friendsEntity = (FriendsEntity)Translate.ByteToObject(cn.edu.ldu.protocol.getData());
            FriendsEntity friendsEntity = JSON.parseObject(protocol.getData(), FriendsEntity.class);
            L.OK(friendsEntity, FriendsEntity.class);
            if(friendsEntity.getStatus() == null || friendsEntity.getStatus() == 0){
                if(!UserController.sendDataToUser(friendsEntity.getFriendId(),protocol))
                    friendsEntity.setStatus(0);
                else{
                    friendsEntity.setStatus(1);
//                    protocol.setKey(Consts.P_FRIEND_ONALINE);
//                    protocol.setPacket(p);
//                    UserController.sendDataToUser(protocol);
                }
                UserAccountEntity u = UserAccountController.getUserAccount(friendsEntity.getFriendId(), protocol.getToken());
                friendsEntity.setUserAccountEntity(u);
                FriendsController.addFriend(friendsEntity, protocol.getToken());
            }else {   //修改数据库——status：1
                FriendsController.updateFriend(friendsEntity, protocol.getToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
